import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {Navigator, Picker, Text, View} from '@tarojs/components'
import {IDENTITY, INVOICE_PAGE, INVOICE_DELETE, TARO_ENV} from '../../../constants/api'
import {newHttp} from "../../../utils/request";
import {http} from "../../../utils/http";
import {UserIdentity} from "../../../utils/server.interface";
import {user} from "../../../utils/user.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../../utils/tools";
import './list.scss'

interface StateType {
  show: boolean
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  queryData: {
    supplier_id: string
    reserveDateEnd: string
    order_num: string
    reserveDate: string
    reserveStatus: string
    link_phone: string
    link_name: string
    goods_name: string
    length: number
    page: number
  }
  supplierIndex: number
  supplierChecked: string
  inputText: string
  listData: any
  supplierList: any
  isFirst: boolean
}

export default class ManageAppointment extends Component {
  state: StateType = {
    loadMoreStatus: 'loading',
    queryData: {
      supplier_id: '',
      length: 10,
      page: 1
    },
    supplierChecked: '',
    supplierIndex: 0,
    show: false,
    inputText: '',
    listData: [],
    supplierList: [],
    isFirst: true
  }
  page = 1

  async componentDidShow() {
    this.page = 1
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    } else {
      const userIdentity: any = await http.get<UserIdentity>(IDENTITY, {})
      if (userIdentity && userIdentity.isSupplier) {
        let supplierChecked = ''
        let supplierIndex = Taro.getStorageSync('mySupplierIndex') || 0
        if (userIdentity.SupplierList.length > 0) {
          supplierIndex = userIdentity.SupplierList.length < supplierIndex ? userIdentity.SupplierList.length - 1 : supplierIndex
          supplierChecked = userIdentity.SupplierList[supplierIndex].company
          this.state.queryData.supplier_id = userIdentity.SupplierList[supplierIndex].supplier_id
          Taro.setStorageSync('mySupplierIndex', supplierIndex)
        }
        this.setState({supplierList: userIdentity.SupplierList, supplierChecked, supplierIndex})
      } else {
        Taro.showToast({
          title: '您还没有供应商，请确认用户身份',
          icon: 'none',
          mask: true
        })
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 1500)
        return
      }
    }
    this.getListData(this.state.queryData)
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const {queryData} = this.state
      this.page++
      queryData['page'] = this.page
      const old = this.state.listData
      const data = await newHttp.get(INVOICE_PAGE, queryData)
      if (data.data.length < queryData.length) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      this.setState({queryData, listData: [...old, ...data.data]})
    }
  }

  async getListData(queryData) {
    Taro.showLoading({title: '加载中'})
    const data = await newHttp.get(INVOICE_PAGE, queryData)
    if (JSON.stringify(data) !== '{}'){
      if (data.data.length < queryData.length) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      this.setState({queryData, listData: data.data})
    } else {
      this.setState({queryData, listData: []})
    }
    Taro.hideLoading()
  }

  handleChange(field, val) {
    if (typeof val === 'object') {
      val = val.detail.value
    }
    const {queryData} = this.state
    queryData[field] = val
    this.setState({queryData})
  }

  handleForm() {
    const {queryData} = this.state
    this.page = 1
    queryData['page'] = 1
    this.getListData(queryData)
  }

  onChange(e) {
    const {supplierList, queryData} = this.state
    this.page = 1
    const supplierIndex = Number(e.detail.value)
    const supplierChecked = supplierList[supplierIndex].company
    queryData['page'] = 1
    queryData['supplier_id'] = supplierList[supplierIndex].supplier_id
    this.setState({supplierIndex, supplierChecked})
    Taro.setStorageSync('mySupplierIndex', supplierIndex)
    this.getListData(queryData)
  }

  inputChange(e) {
    const {queryData} = this.state
    queryData['search_supplier'] = e.detail.value
    this.setState({queryData})
  }

  jump(url) {
    Taro.navigateTo({
      url
    })
  }

  delInvoice(id){
    const that = this
    Taro.showModal({
      title: '提示',
      content: '确认要删除此发票吗？',
      success: async function (res) {
        if(res.confirm){
          const res = await http.HPost(INVOICE_DELETE,{id})
          if (res){
            Taro.showToast({ title: '操作成功', mask: true })
            setTimeout(async ()=> {
              that.state.queryData.page = 1
              await that.getListData(that.state.queryData)
            }, 2000)
          }
        }
      }
    })
  }

  downLoadFile(url) {
    // if (TARO_ENV === 'h5'){
      Taro.navigateTo({ url: '/main/my/requestInvoice/downlode?url=' + url })
    // } else {
    //   Taro.downloadFile({
    //     url,
    //     success: function (res) {
    //       const filePath = res.tempFilePath
    //       Taro.openDocument({
    //         filePath: filePath,
    //         success: function (res) {
    //           Taro.showToast({ title: '保存成功!' })
    //         }
    //       })
    //     }
    //   })
    // }
  }

  render() {
    const {supplierList, supplierChecked, supplierIndex, listData, queryData} = this.state
    return (
      <View className='root yuyue-root'>
        <GzhAuth />
        <View className='header-top' style={`background-color: ${process.env.mainColor}`}>
          <View className='head-picker'>
            {supplierList.length >= 1 &&
            <Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
              <View className={supplierChecked ? 'picker' : 'picker off'}>
                {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                <Text>切换</Text>
              </View>
            </Picker>}
          </View>
        </View>
        {listData && listData.length > 0 &&
        <View className='article-body'>
          {listData.map((item) =>
            <View className='article-item' key={item.index} key={item.index}>
              <View className='article-body-header'>
                <View className='header-right'>
                  { (item.state === 0 || item.invoice_url) ? <Text className='normal-text'>{ item.state === 0 ? '待审核' : '已通过' }</Text> : <Text className='normal-text refuse-text'>已拒绝</Text> }
                </View>
                <View className='header-left'>{item.invoicetitle_name}</View>
              </View>
              <View className='line' />
              <View className='goods-item'>发票类型：普通发票</View>
              {item.invoicetitleType && <View className='goods-item'>抬头类型：{item.invoicetitleType}</View>}
              {item.addDate && <View className='goods-item'>申请时间：{item.addDate}</View>}
              {item.refuse_cause && <View className='goods-item goods-item-refuse'>原因：{item.refuse_cause}</View>}
              <View className='btnGroup'>
                {item.invoice_url && <View className='arrangement' onClick={this.downLoadFile.bind(this, item.invoice_url)}>
                  <View className='arrangement-btn'>下载发票</View>
                </View>}
                {!!item.state && <View className='arrangement' onClick={this.delInvoice.bind(this, item.id)}>
                  <View className='arrangement-btn'>删除</View>
                </View>}
                <View className='arrangement' onClick={this.jump.bind(this, '/main/my/requestInvoice/info?id=' + item.id + `&supplierId=${queryData.supplier_id}`)}>
                  <View className='arrangement-btn'>详情</View>
                </View>
              </View>
            </View>
          )}
        </View>}
        {listData.length <= 0 && <View className='no-data'>您还没有申请发票信息</View>}
        <View style='height: 50px' />
        <Navigator className='btn-box-result' style={`background-color: ${process.env.mainColor}`} url={`/main/my/requestInvoice/info?supplierId=${queryData.supplier_id}`}>
          <Text>申请发票</Text>
        </Navigator>
      </View>
    )
  }
}
